package com.hsj.mqconsumer.consumer;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * 消息拒绝 消费者
 * @author:Teacher黄
 * @date:Created at 2020/01/05
 */
@Component
public class RejectConsumer {

    /**
     * 计数器
     */
    private Integer num = 1;


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "reject_queue",durable = "true",autoDelete = "true"),
            exchange = @Exchange(name = "reject_exchange",type = "topic"),
            key = "reject.*"
    ))
    @RabbitHandler
    public void reject(String msg, @Headers Map<String,Object> headers, Channel channel) throws IOException {
        long deliverTag = (long) headers.get(AmqpHeaders.DELIVERY_TAG);
        if(num <= 5){
            num++;
            System.out.println("接收到了消息:"+msg+"=====继续入队"+num);
            channel.basicReject(deliverTag,true);
        }else {
            System.out.println("接收到了消息:"+msg+"=====不在入队"+num);
            channel.basicReject(deliverTag,false);
        }


    }

}
